<template>
  <el-header class="header-wrap" height="48px">
    <el-image
      id="img-buffer"
      :src="iconSrc"
      alt="二维码图标"
      style="width: 250px; height: 250px;display: none;"
      @error="iconError"
    ></el-image>
    <div class="logo-link">
      <img alt="LOGO" :src="logoSrc" width="100%" height="100%" @error="logoError" />
    </div>
    <div class="menu-nav-wrap">
      <header-nav :addTab="addTab"></header-nav>
      <div class="time-wrap">
        <img v-if="showRemoteControl" src="@/assets/images/home/remoteControl.png" title="远程控制" @click="openRemoteControl" style="margin-right:15px;cursor:pointer;">
        <span v-if="isShowElevatorControl" class="iconfont icon-dianti01" title="梯控" @click="openElevatorController"></span>
        <span v-if="isShowCall" class="el-icon el-icon-phone" title="呼叫中心" @click="openCallCenter(null)"></span>
        <span v-popover:popover class="iconfont icon-weibiaoti--3" title="关闭警情" @click="menu_alarm_click"></span>
        <!-- 视频 -->
        <span v-if="hasVideo" class="iconfont icon-camera" title="视频" @click="menu_vedio_click"></span>
        <img
          v-if="bsUrl"
          src="resource/icon-bs.png"
          title="大屏"
          width="30"
          style="margin-right:20px;cursor:pointer;"
          @click="openBs"
        />
        <!-- 消息--暂时搁置 -->
        <!-- <span class="iconfont icon-message" @click="openMessage"></span> -->
        <el-dropdown class="userinfo-wrap" @command="handleCommand">
          <span class="el-dropdown-link">
            <span class="user-name">{{ accountNameRight }}</span>
            <img class="header-user-img" :src="headUrlRight || defaultUserHead" />
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="messageNotification">
              消息提醒
              <el-switch
                v-model="notificationSwitch"
                active-color="#13ce66"
                @change="changeNotificationSwitch"
                style="margin-left: 20px;"
              ></el-switch>
              <el-checkbox
                class="mute-checkbox"
                v-show="notificationSwitch"
                v-model="isMute"
                style="margin-left: 5px;"
                @change="changeMuteState"
              >静音</el-checkbox>
            </el-dropdown-item>
            <el-dropdown-item command="showDialogBaseInfo">基本资料</el-dropdown-item>
            <el-dropdown-item command="subscribe">警情订阅</el-dropdown-item>
            <el-dropdown-item command="showDialogChangePsw">修改密码</el-dropdown-item>
            <el-dropdown-item divided command="downloadApp">应用下载</el-dropdown-item>
            <el-dropdown-item divided command="clearCache">清除缓存</el-dropdown-item>
            <el-dropdown-item divided command="logout">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="基本资料"
      width="500px"
      top="20vh"
      :visible.sync="dialogBaseInfo"
      @close="closeBaseInfo"
    >
      <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
          <el-form
            label-width="110px"
            :model="baseInfoForm"
            :rules="baseInfoFormRules"
            ref="baseInfoForm"
            @submit.native.prevent
          >
            <el-form-item label="账号：" prop="accountName">
              <el-input v-model="accountName" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="职位：" prop="postName">
              <el-input v-model="postName" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色：" prop="roleName">
              <el-input v-model="roleName" auto-complete="off" placeholder="请输入账号" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户名称：" prop="name">
              <el-input v-model="baseInfoForm.name" auto-complete="off" placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <el-form-item label="联系电话：" prop="tel">
              <el-input v-model="baseInfoForm.tel" auto-complete="off" placeholder="请输入联系电话"></el-input>
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="baseInfoForm.email" auto-complete="off" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="身份证号：" prop="card">
              <el-input v-model="baseInfoForm.card" auto-complete="off" placeholder="请输入身份证号"></el-input>
            </el-form-item>
            <el-form-item label-width="0" class="verifyidentity-button">
              <el-button @click="closeBaseInfo">取消</el-button>
              <el-button type="primary" @click="updateBaseInfo('baseInfoForm')">确定</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="修改密码"
      width="550px"
      top="25vh"
      :visible.sync="dialogChangePsw"
      @close="closeChangePsw"
    >
      <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
          <el-form
            label-width="110px"
            :model="changePswForm"
            :rules="changePswFormRules"
            ref="changePswForm"
            @submit.native.prevent
          >
            <el-form-item label="旧密码：" prop="oldPsw">
              <el-input
                type="password"
                v-model="changePswForm.oldPsw"
                auto-complete="off"
                placeholder="请输入旧密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="新密码：" prop="newPsw">
              <el-input
                type="password"
                v-model="changePswForm.newPsw"
                auto-complete="off"
                placeholder="请输入新密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码：" prop="againPsw">
              <el-input
                type="password"
                v-model="changePswForm.againPsw"
                auto-complete="off"
                placeholder="请输入确认密码"
                show-password
              ></el-input>
            </el-form-item>
            <p class="color-2">密码规则：6~16位英文、“-”、“_”或数字&nbsp;&nbsp;&nbsp;&nbsp;不允许有空格&nbsp;&nbsp;&nbsp;&nbsp;不允许有中文</p>
            <el-form-item label-width="0" class="verifyidentity-button">
              <el-button @click="closeChangePsw">取消</el-button>
              <el-button type="primary" @click="updatePsw('changePswForm')">提交</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="智慧消防平台"
      width="500px"
      top="25vh"
      :visible.sync="dialogDownload"
      @close="closeDownload"
    >
      <el-row type="flex" justify="center" class="form-download">
        <el-tabs v-loading="loading" @tab-click="handleTabClick">
          <el-tab-pane label="手机客户端下载">
            <div class="qrcode-content">
              <div id="container_ios">
                <vue-qr
                  :logoMargin="2"
                  logoBackgroundColor="rgb(255,255,255)"
                  :logoSrc="iconSrc"
                  :text="iosUrl"
                  :size="160"
                  :margin="0"
                  :dotScale="0.75"
                ></vue-qr>
              </div>
              <div class="ios-btn"></div>
            </div>
            <div class="qrcode-content">
              <div id="container_android" style="padding-left: 5px;">
                <vue-qr
                  :logoMargin="2"
                  logoBackgroundColor="rgb(255,255,255)"
                  :logoSrc="iconSrc"
                  :text="androidUrl"
                  :size="160"
                  :margin="0"
                  :dotScale="0.75"
                ></vue-qr>
              </div>
              <div class="android-btn"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="平台客户端下载">
            <div class="qrcode-content" style="width: 100%;">
              <div
                @click="downloadPcClient"
                class="planClient-btn"
                :style="{ backgroundImage: 'url(' + planClientSrc + ')' }"
              ></div>
              <p>最新版本：{{latestVersionName}}</p>
              <p>点击图标下载到本地</p>
              <p v-if="isClientLatest" class="text-center" style="margin-top:20px;color:red;">当前已是最新版本</p>
              <p
                v-else-if="localVersionName"
                class="text-center"
                style="margin-top:10px;color:red;"
              >当前版本：{{localVersionName}}</p>
            </div>
          </el-tab-pane>
          <el-tab-pane label="视频客户端下载">
            <div class="qrcode-content" style="width: 100%;">
              <div @click="downloadVedioClient" class="videoClient-btn"></div>
              <p>最新版本：{{latestVideoVersionName}}</p>
              <p>点击图标下载到本地</p>
              <p v-if="isVideoClientLatest" class="text-center" style="margin-top:10px;color:red;">当前已是最新版本</p>
              <p
                v-else-if="localVideoVersionName"
                class="text-center"
                style="margin-top:10px;color:red;"
              >当前版本：{{localVideoVersionName}}</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </el-dialog>
    <!-- 关闭警情提醒弹窗 -->
    <el-popover
      ref="popover"
      v-model="alarmRemindVisible"
      popper-class="popover_diaglo"
      placement="bottom"
      :title="policeTitle"
      :width="policeWidth"
      trigger="click"
      content
    >
      <div class="header_police_history">
        <el-button v-if="realTime_history" @click="showHistory" type="text">查看历史记录></el-button>
        <el-button v-if="history_realTime" @click="showRealTime_history" type="text">返回></el-button>
        <!-- <span v-if="realTime_history" @click="showHistory">查看历史记录></span> -->
      </div>
      <el-table
        :data="policeTableData"
        border
        :cell-style="tableRowClassName"
        v-if="realTime_history"
        v-loading="loading"
        style="width: 100%;"
      >
        <el-table-column label="序号" width="50" type="index"></el-table-column>
        <el-table-column prop="type" class="police_type" label="状态"></el-table-column>
        <el-table-column prop="orgName" label="联网单位"></el-table-column>
        <el-table-column prop="systemName" label="系统"></el-table-column>
        <el-table-column prop="fbsName" label="建筑物"></el-table-column>
        <el-table-column prop="beginTime" width="160" label="时间段"></el-table-column>
        <el-table-column label="屏蔽用户角色">
          <template slot-scope="scope">
            <div
              :title="scope.row.roleNames"
              style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 3;-webkit-box-orient: vertical;"
            >{{ scope.row.roleNames }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createName" width="90" label="创建人"></el-table-column>
        <el-table-column label="事由">
          <template slot-scope="scope">
            <div
              :title="scope.row.remark"
              style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 3;-webkit-box-orient: vertical;"
            >{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleDetail(scope.row)" type="text" size="small">提前结束</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="policeHistoryTableData" border v-if="history_realTime" style="width: 100%">
        <el-table-column label="序号" width="50" row-style="height:80px" type="index"></el-table-column>
        <el-table-column prop="type" width="90" label="状态"></el-table-column>
        <el-table-column prop="orgName" label="联网单位"></el-table-column>
        <el-table-column prop="systemName" label="系统"></el-table-column>
        <el-table-column prop="fbsName" label="建筑物"></el-table-column>
        <el-table-column prop="beginTime" width="160" label="时间段"></el-table-column>
        <el-table-column label="屏蔽用户角色">
          <template slot-scope="scope">
            <div
              :title="scope.row.roleNames"
              style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 3;-webkit-box-orient: vertical;"
            >{{ scope.row.roleNames }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createName" width="90" label="创建人"></el-table-column>
        <el-table-column label="事由">
          <template slot-scope="scope">
            <div
              :title="scope.row.remark"
              style="overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 3;-webkit-box-orient: vertical;"
            >{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
      </el-table>
      <span v-if="realTime_history">
        <el-button style="margin-left: 49%;margin-top: 15px;" type="primary" @click="addPolice">新增</el-button>
      </span>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        v-if="history_realTime"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <div v-if="dailogAddpolice">
        <el-form
          :ref="savehForm"
          :rules="savehFormRules"
          label-width="150px"
          :inline="true"
          :model="savehForm"
          @close="closeDialog"
          @submit.native.prevent
        >
          <el-form-item label="选择联网单位：" prop="orgId">
            <el-select class="input_length" filterable v-model="savehForm.orgId" placeholder="请选择单位">
              <el-option
                v-for="item in orgOptions"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择系统：" prop="fireSystemId">
            <el-select
              class="input_length"
              :disabled="selectFlag"
              filterable
              v-model="savehForm.fireSystemId"
              placeholder="选择系统"
            >
              <el-option
                v-for="item in typeList"
                :key="item.fireSystemId"
                :label="item.fireSystemName"
                :value="item.fireSystemId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择建筑物：" prop="build">
            <tree-select
              v-model="savehForm.build"
              placeholder="选择建筑物"
              filterable
              class="build_tree"
              :disabled="selectFlag"
              :width="480"
              :data="treeData"
              :defaultProps="defaultProps"
              :checkedKeys="defaultCheckedCategoryId"
              :nodeKey="typeNodeKey"
            ></tree-select>
          </el-form-item>
          <el-form-item label="选择屏蔽的角色：" prop="roles">
            <el-select
              class="input_length"
              :disabled="selectFlag"
              filterable
              multiple
              v-model="savehForm.roles"
              placeholder="选择屏蔽的用户角色"
            >
              <el-option v-for="item in rolesOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择时间范围：" prop="time">
            <el-date-picker
              v-model="savehForm.time"
              type="datetimerange"
              align="right"
              :disabled="selectFlag"
              unlink-panels
              class="input_length"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <div class="head_police_remind">请设置在24小时以内</div>
          <el-form-item label="事由" prop="remark">
            <el-input style="width:504px;" v-model="savehForm.remark" placeholder="事由"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button style="margin-left: 41%;" @click="cancelPolice">关 闭</el-button>
          <el-button type="primary" @click="savePolice(savehForm)">保存</el-button>
        </span>
      </div>
    </el-popover>
    <!-- 呼叫中心 -->
    <el-drawer title="呼叫中心" :visible.sync="drawer" :before-close="closeCallCenter" append-to-body>
      <call-center :parames="callCenterParames"></call-center>
    </el-drawer>
    <!-- 梯控中心 -->
    <el-drawer title="梯控" append-to-body :visible.sync="elevatorVisible" :before-close="closeElevatorController">
      <elevator-center
        :formInline="formInline"
        :handleFormVisible="handleFormVisible"
        @showHandleForm="showHandleForm"
        @hideHandleForm="hideHandleForm"
      ></elevator-center>
    </el-drawer>
    <!-- 远程控制 -->
    <el-drawer title="远程控制" append-to-body :visible.sync="remoteControlVisible">
      <remote-controller/>
    </el-drawer>
    <!-- 推送的提示声音 -->
    <audio
      id="audioPlayer"
      :src="currentAudioUrl"
      autoplay
      controls
      @error="playAudioError()"
      @ended="playAudioEnd()"
      :paused="audioPaused"
      style="display: none;"
    ></audio>
    <!-- 视频分析图片预览 -->
    <image-viewer ref="ImageViewer" :origin-list="originList"></image-viewer>
    <!-- 警情订阅弹窗 -->
    <subscribe v-if="subscribeVisible" ref="subscribe"></subscribe>
  </el-header>
</template>
<script>
import HeaderNav from '@/components/Nav/Main'
import { validphone, isvalidPassword } from '@/utils/validate'
import util from '@/utils/util'
import { logout, updateUserInfo, updatePwd, getNewAppV } from '@/api/api'
import ReconnectingWebSocket from 'reconnecting-websocket'
import { getOrgList } from '@/api/org'
import { getSysFcfCategoryTree } from '@/api/fcf'
import { getFbsTree } from '@/api/sysConfig'
import TreeSelect from '@/libs/TreeSelect/Main'
import {
  getPoliceCloseRecords,
  endPoliceClose,
  getUnitRoles,
  saveOrUpdatePoliceCloseRecord,
} from '@/api/alarm'
import CallCenter from './Dialog/CallCenter'
import ElevatorCenter from './Dialog/ElevatorController'
import ImageViewer from '@/components/TransAiPic/ImageViewer'
import Subscribe from './Subscribe'
import RemoteController from './Dialog/RemoteController'

var t = null
window.ws ? window.ws.close() : ''
let bsUrl = typeof BSURL == 'undefined' ? false : BSURL
export default {
  name: 'HeaderBar',
  props: ['addTab'],
  components: {
    HeaderNav,
    TreeSelect,
    CallCenter,
    ElevatorCenter,
    ImageViewer,
    Subscribe,
    RemoteController
  },
  data() {
    const validatePhoneNum = (rule, value, callback) => {
      if (!validphone(value)) callback(new Error('请输入正确的手机号'))
      callback()
    }
    var validateNewPsw = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (
        !isvalidPassword(value) ||
        value.length < 6 ||
        value.length > 16
      ) {
        callback(new Error('请输入正确的密码格式'))
      } else {
        if (this.changePswForm.oldPsw === this.changePswForm.newPsw) {
          this.changePswForm.newPsw = ''
          callback(new Error('新密码不能和旧密码一致'))
        }
        callback()
      }
    }
    var validateAgainPsw = (rule, value, callback) => {
      if (this.changePswForm.newPsw !== this.changePswForm.againPsw) {
        callback(new Error('新密码与确认密码不一致'))
        this.changePswForm.againPsw = ''
      } else {
        callback()
      }
    }
    return {
      showRemoteControl:false,
      remoteControlVisible:false,
      subscribeVisible: false,
      bsUrl: bsUrl,
      isClientLatest: false,
      latestVersionName: '',
      localVersionName: '',
      isVideoClientLatest: false,
      latestVideoVersionName: '',
      localVideoVersionName: '',
      elevatorVisible: false, // 梯控中心是否可见
      formInline: {
        orgIds: '', // 联网单位id编码，空表示所有
        fbsId: '', // 建筑物id
        queryContent: '', // 搜索内容
        status: 2, // 状态 2触发 3禁用 4正常 5离线
        queryType: 1, // 是否做分页 0不做分页 1做分页
        pageIndex: 0, // 当前页 起始页0开始
        pageSize: 10, // 每页显示数目
      },
      handleFormVisible: false,

      loading: false,
      platOnlyKey: '',
      hasVideo: false, // 是否有监控
      defaultUserHead: require('../../assets/images/default/userHead.png'),
      logoSrc: '',
      iconSrc: '',
      planClientSrc: '',
      iosUrl: '',
      androidUrl: '',
      accountNameRight: '',
      headUrlRight: '',
      accountName: '',
      postName: '',
      dialogBaseInfo: false,
      dialogChangePsw: false,
      dialogDownload: false,
      dialogPolice: false,
      history_realTime: false,
      dailogAddpolice: false,
      weibiaotiflag: true,
      roleName: '',
      selectFlag: true,
      baseInfoForm: {
        id: '',
        name: '',
        tel: '',
        email: '',
        card: '',
      },
      changePswForm: {
        oldPsw: '',
        newPsw: '',
        againPsw: '',
      },
      baseInfoFormRules: {
        name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
        tel: [
          {
            required: true,
            validator: validatePhoneNum,
            trigger: ['blur', 'change'],
          },
        ],
        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'blur' },
        // ],
        card: [],
      },
      changePswFormRules: {
        oldPsw: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        newPsw: [
          { required: true, validator: validateNewPsw, trigger: 'blur' },
        ],
        againPsw: [
          { required: true, validator: validateAgainPsw, trigger: 'blur' },
        ],
      },
      savehFormRules: {
        orgId: [{ required: true, message: '请选择单位', trigger: 'blur' }],
        //fireSystemId:[{ required: true, message: '请选择系统', trigger: 'blur' },],
        build: [{ required: true, message: '请选择建筑物', trigger: 'blur' }],
        time: [{ required: true, message: '请选择屏蔽时间', trigger: 'blur' }],
        roles: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
      },
      // pushAlarmDialogVisible: false,
      // pushAlarmDialogData:{},
      // pushAlarmDialogTitle:'收到新警情！',
      policeTableData: [], //关闭警情提醒列表执行中
      policeHistoryTableData: [], //关闭警情提醒列表执行中
      total: 0,
      currentPage: 1,
      pageSize: 10,
      policeTitle: '未结束的关闭措施',
      realTime_history: true, //历史记录和实时情况的flag
      savehForm: {
        orgId: '',
        fireSystemId: '',
        build: '',
        time: '',
        roles: '',
        remark: '',
      },
      orgOptions: [], //单位下拉框
      rolesOptions: [], //角色下拉框
      typeList: [], // 消防系统
      defaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      treeData: [],
      policeWidth: '1200',
      pickerOptions: {
        disabledDate: (time) => {
          let nowData = new Date()
          nowData = new Date(nowData.setDate(nowData.getDate()))
          // 因为time返回的默认时间是00:00:00 所以加上23:59:59
          return (
            time.getTime() + 1000 * 60 * 60 * 23 + 1000 * 60 * 59 + 59 * 1000 <
            nowData.getTime()
          )
        },
      },
      alarmRemindVisible: false, // 关闭警情题型弹出层的显示隐藏
      notificationSwitch: true, // 开关消息提醒
      firstLoadAudio: true, // 是否首次播放音频
      isMute: true, // 是否静音
      currentAudioUrl: require('../../assets/alarm.ogg'),
      audioPaused: false, // 是否暂停
      audioIsPlaying: false, // 是否正在播放
      currentNotification: [],
      drawer: false, // 呼叫中心显示
      callCenterParames: {}, // 打开呼叫中心附带参数
      isShowElevatorControl: false, // 显示梯控
      isShowCall: false, // 显示呼叫中心
      originList: [],
    }
  },
  created() {
    if(typeof SHOW_REMOTE_CONTROL!=='undefined'){
      this.showRemoteControl=SHOW_REMOTE_CONTROL
    }
    this.alarmMap = {}
    this.isShowElevatorControl = SHOW_ELEVATOR_CONTROL
    this.isShowCall = SHOW_CALL_CENTER
    let roleNameArr = []
    let that = this
    if (that.$store.state.userinfo) {
      that.accountNameRight = that.$store.state.userinfo.name
      that.headUrlRight = that.$store.state.userinfo.headUrl
      that.accountName = that.$store.state.userinfo.accountName
      that.postName = that.$store.state.userinfo.postName
      that.formInline = {
        orgIds: that.$store.state.userinfo.organizationIds, // 联网单位id编码，空表示所有
        fbsId: '', // 建筑物id
        queryContent: '', // 搜索内容
        status: 2, // 状态 2触发 3禁用 4正常 5离线
        queryType: 1, // 是否做分页 0不做分页 1做分页
        pageIndex: 0, // 当前页 起始页0开始
        pageSize: 10, // 每页显示数目
      }
      that.baseInfoForm = {
        id: that.$store.state.userinfo.id,
        name: that.$store.state.userinfo.name,
        tel: that.$store.state.userinfo.phone,
        email: that.$store.state.userinfo.email,
        card: that.$store.state.userinfo.idCardNo,
      }
      that.planClientSrc =
        REMOTESTATICPATH +
        that.$store.state.userinfo.loginId +
        '/pc/login/download/plat.png'

      that.logoSrc =
        REMOTESTATICPATH +
        that.$store.state.userinfo.loginId +
        '/pc/home/home.png'
      that.iconSrc =
        REMOTESTATICPATH +
        that.$store.state.userinfo.loginId +
        '/pc/qrCode/qr.png'

      that.platOnlyKey =
        localStorage.getItem('ilink_platformCode_platId') ||
        that.$store.state.userinfo.org.id

      that.menu_alarm_click()
      for (
        let i = 0, len = that.$store.state.userinfo.role.length;
        i < len;
        i++
      ) {
        roleNameArr.push(that.$store.state.userinfo.role[i].name)
      }
      that.roleName = roleNameArr.join('、')

      if (typeof WebSocket === 'undefined') {
        console.log('您的浏览器不支持socket')
      } else {
        that.int_webSocket()
      }

      let menuList = that.$store.state.userinfo.resources || []
      for (var i = 0, len = menuList.length; i < len; i++) {
        if (menuList[i].link === 'videoMonitor') {
          that.hasVideo = true
          return false
        }
      }
    }
  },
  mounted() {
    // 暴露打开呼叫中心方法
    window.openCallCenter = this.openCallCenter
    window.jumpeToUnresetAlarm = this.jumpeToUnresetAlarm
    window.FuncPreviewPushImage = this.handlePreviewPushImage
    window.pushAlarmPopup = this.pushAlarmPopup
    window.FuncDealAlarm = this.FuncDealAlarm
    const data = {
      createTime: 1600064329771, //发生时间
      // desc: '通信服务器:通信服务,机号:1,回路:060,点位:090设备发生警情，由于该设备未录入到系统，请通过报警主机查看详情，请前往现场了解情况',
      desc: '请前往现场了解情况',
      name: '通信服务器:通信服务,机号:1,回路:060,点位:090', //描述
      orgId: 176, //是否复位（0离线  1复位（需要在描述后拼接复位））
      time: '19:39:46',
      organizationId: 176,
      organizationName: '哈哈',
      resetTime: 1600064329771, //复位时间（如果是复位采用复位时间）
      type: 1, //标识用传在离线
      messageType: 1,
    }
    window.unenteredEquipment = () => {
      this.unenteredEquipment(data)
    }
    window.mockAlarm = () => {
      this.pushAlarmPopup({
        id: '1',
        createTime: '2021-01-20 10:52:47',
        dataFlag: 1,
        fcFacilitiesId: '2192926',
        fcFacilitiesName: '危险品分析摄像头9-2',
        fireTType: '10',
        organizationName: '金城花园',
        picturesUrls:
          'http://121.43.159.40:8899/2021012010/1611111167708705.jpg',
        selfDesc: '9幢>电梯2危险品分析摄像头9-2电瓶车上楼',
        messageType: 1,
      })
    }
    window.openInspectNotify = this.openInspectNotify
  },
  methods: {
    openRemoteControl(){
      this.remoteControlVisible=true
    },
    subscribe() {
      this.subscribeVisible = true
      this.$nextTick(() => {
        this.$refs.subscribe.init()
      })
    },
    FuncDealAlarm(e) {
      window.event.stopPropagation()
      let obj = this.alarmMap[e.getAttribute('data-id')]
      if (obj) {
        this.jumpeToUnresetAlarm(
          obj.notifyType,
          obj.key,
          { ...obj.data, fcFacilitiesName: '' },
          e.getAttribute('data-type')
        )
      }
    },
    handleTabClick(tab) {
      if (tab.label === '平台客户端下载') {
        this.getClientVersion()
      } else if (tab.label === '视频客户端下载') {
        this.getVideoClientVersion()
      }
    },
    getClientVersion() {
      // 本地客户端版本号
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 4,
      }).then((res) => {
        if (res.data) {
          this.latestVersionName = res.data.softName
          if (typeof ILINK_CLIENT_VERSION_NAME != 'undefined') {
            this.localVersionName = ILINK_CLIENT_VERSION_NAME
            this.isClientLatest =
              res.data.softNumber <= Number(ILINK_CLIENT_VERSION)
          }
        }
      })
    },
    getVideoClientVersion() {
      // 本地视频客户端版本号
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 3,
      }).then((res) => {
        if (res.data) {
          this.latestVideoVersionName = res.data.softName
          if (typeof ILINK_VIDEO_CLIENT_VERSION != 'undefined') {
            this.localVideoVersionName = ILINK_VIDEO_CLIENT_VERSION_NAME || ''
            this.isVideoClientLatest =
              res.data.softNumber <= Number(ILINK_VIDEO_CLIENT_VERSION)
          }
        }
      })
    },
    // 打开呼叫中心
    openCallCenter(data) {
      if (data) {
        this.callCenterParames = data
      } else {
        this.callCenterParames = {}
      }
      this.drawer = true
    },
    // 关闭呼叫中心
    closeCallCenter() {
      this.drawer = false
    },
    logoError(e) {
      this.logoSrc = REMOTESTATICPATH + PLATCOEDEFAULT + '/pc/home/home.png'
      this.planClientSrc =
        REMOTESTATICPATH + PLATCOEDEFAULT + '/pc/login/download/plat.png'
    },
    iconError(e) {
      this.iconSrc = REMOTESTATICPATH + PLATCOEDEFAULT + '/pc/qrCode/qr.png'
    },
    openMessage() {
      this.$message({
        message: '该功能暂未开放！',
        type: 'warning',
      })
    },
    downloadApp() {
      this.loading = true
      // 二维码中插入图标；根据分平台载入不同图标
      this.dialogDownload = true
      //IOS
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 1,
      }).then((res) => {
        this.loading = false
        if (res.data && res.data.url) {
          this.iosUrl = res.data.url
        }
      })
      //安卓
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 2,
      }).then((res) => {
        this.loading = false
        if (res.data && res.data.url) {
          this.androidUrl =
            window.location.origin +
            '/ilink/download/download.html?organizationId=' +
            res.data.organizationId +
            '&platformCode=' +
            (this.$store.state.userinfo.loginId || PLATCOEDEFAULT) +
            '&softName=' +
            res.data.softName +
            '&url=' +
            res.data.url
        }
      })
    },
    downloadPcClient() {
      //pc客户端
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 4 /* this.$store.state.userinfo.isMuilUnitUser?4:6 */,
      }).then((res) => {
        if (res.data && res.data.url) {
          location.href = res.data.url
        } else {
          this.$message({
            message: '暂无相关资源！',
            type: 'warning',
          })
        }
      })
    },
    downloadVedioClient() {
      //视频客户端
      getNewAppV({
        organizationId: this.platOnlyKey,
        type: 3,
      }).then((res) => {
        if (res.data && res.data.url) {
          location.href = res.data.url
        } else {
          this.$message({
            message: '暂无相关资源！',
            type: 'warning',
          })
        }
      })
    },
    closeDownload() {
      this.dialogDownload = false
    },
    logout() {
      logout({}).then((skipPageType) => {
        //skipPageType 0:单单位  1:多单位
        let userinfo =
          (localStorage.getItem('userInfo')
            ? JSON.parse(localStorage.getItem('userInfo'))
            : '') || this.$store.state.userinfo
        localStorage.removeItem('userInfo')
        // 关闭全部推送消息
        this.closeAllNotify()
        // 断开webscoket
        window.ws ? window.ws.close() : ''
        this.$router.push({
          path: '/login',
          query: userinfo
            ? userinfo.loginId
              ? { loginId: userinfo.loginId }
              : {}
            : {},
        })
      })
    },
    handleCommand(command) {
      if (command != 'messageNotification') {
        this[command]()
      }
    },
    clearCache() {
      // 触发客户端清除缓存，此代码不能删除！
      console.log('清除客户端缓存')
    },
    menu_vedio_click() {
      util.menu_vedio_click()
    },
    openBs() {
      let platformCode = this.GLOBAL.getPlatFormCodeByUrl()
      var objStr = JSON.stringify({
        accountName: this.$store.state.userinfo.accountName,
        password: this.$store.state.userinfo.password,
        platformCode,
      })
      var url = `ilink-client:` + encodeURI(objStr.replace(/"/gm, "'"))
      if (window.external.openVedioClient) {
        window.external.openVedioClient(url)
      } else {
        location.href = url
        // location.href=`${bsUrl}?loginId=${platformCode}&account=${this.$store.state.userinfo.accountName}&password=${this.$store.state.userinfo.password}`
      }
    },
    menu_alarm_click(type) {
      //关闭警情推送按钮
      let that = this
      that.loading = true
      getPoliceCloseRecords({
        queryType: 0,
        pageIndex: 0,
        pageSize: 10,
        type: 0,
        orgIds: that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        that.loading = false
        that.policeTableData = res.data
        if (that.policeTableData.length > 0) {
          $('.icon-weibiaoti--3').addClass('iconfont-red')
        } else {
          $('.icon-weibiaoti--3').removeClass('iconfont-red')
        }
        let data = new Date()
        let dataMinutes = data.toLocaleString('chinese', { hour12: false })
        for (var i = 0; i < that.policeTableData.length; i++) {
          if (that.policeTableData[i].status == 0) {
            that.policeTableData[i].type = '未开始'
          } else if (that.policeTableData[i].status == 1) {
            that.policeTableData[i].type = '执行中'
          }
          that.policeTableData[i].beginTime =
            that.policeTableData[i].beginTime.substring(0, 16) +
            ' 至 ' +
            that.policeTableData[i].endTime.substring(0, 16)
        }
      })
    },
    showDialogBaseInfo() {
      this.dialogBaseInfo = true
    },
    showDialogChangePsw() {
      this.dialogChangePsw = true
    },
    // 关闭基本信息弹框
    closeBaseInfo() {
      this.dialogBaseInfo = false
      // 重置基本信息
      this.$refs['baseInfoForm'].resetFields()
    },
    closeDialog() {
      //重置添加警情提醒信息
      this.$refs.savehForm.resetFields()
    },
    // 关闭修改密码弹框
    closeChangePsw() {
      this.dialogChangePsw = false
      // 重置基本信息
      this.$refs['changePswForm'].resetFields()
    },
    updateBaseInfo(formName) {
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          updateUserInfo(that.baseInfoForm).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '修改成功，请重新登录！',
                type: 'success',
              })
              setTimeout(function () {
                that.logout()
              }, 1000)
            } else {
              this.$message.error(res.info)
            }
          })
        } else {
          return false
        }
      })
    },
    updatePsw(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      // 校验
      that.$refs[formName].validate((valid) => {
        if (valid) {
          updatePwd({
            newPassword: that.$md5(that.changePswForm.newPsw),
            oldPassword: that.$md5(that.changePswForm.oldPsw),
            isEncrypt: true,
          }).then((res) => {
            if (res.status === 200) {
              that.$message({
                message: '密码修改成功，请重新登录！',
                type: 'success',
              })
              setTimeout(function () {
                that.logout()
              }, 1000)
            } else {
              that.$message({
                message: res.info,
                type: 'warning',
              })
            }
          })
        }
      })
    },
    int_webSocket() {
      //初始化websocket
      let that = this
      let index = 0
      let _websocketUrl =
        location.origin.replace('https', 'wss').replace('http', 'ws') +
        '/ilink/webSocketServer'
      // 创建websocket连接
      let ws = new ReconnectingWebSocket(_websocketUrl,[],{
        maxReconnectionDelay:300000,
        minReconnectionDelay:30000,
        maxRetries:100
      })
      ws.onopen = function () {
        // console.log("socket开启...");
      }
      ws.onclose = function (event) {
        //console.log("socket关闭...");
      }
      ws.onmessage = function (event) {
        websocketBind(event)
      }
      ws.onerror = function () {
        //console.log("socket出现错误...");
      }
      // 创建websocket绑定分流
      let websocketBind = function (event) {
        let data = JSON.parse(event.data)
        if (data != null) {
          let type = data.type
          let wsData = data.data
          index += 1
          switch (type) {
            case 1002:
              // console.log('推送消息'+ index)
              that.pushAlarmPopup(wsData)
              window.ILINKHOMEWS && window.ILINKHOMEWS(type)
              break
            case 50100:
            case 50101:
            case 50102:
            case 50103:
            case 50104:
            case 50105:
            case 50106:
            case 50200:
            case 50210:
            case 50220:
            case 50230:
            case 50240:
              // 多单位-实时安全评估
              window.ILINKHOMEWS && window.ILINKHOMEWS(type, wsData)
              break
            case 50350:
              // 一键报警推送
              that.pushOneClickAlarmPopup(wsData)
              break
            case 50400:
              // 通信服务器离线推送
              that.pushOffline(wsData)
              break
            case 50500:
              // 未录入设备消息推送
              that.unenteredEquipment(wsData)
              break
            case 50600:
              // 巡检
              that.openInspectNotify(wsData)
              break
            default:
              break
          }
        }
      }
      window.ws = ws
      // 初始化默认静音
      this.$nextTick(() => {
        document.getElementById('audioPlayer').muted = true // 先静音
      })
    },
    openInspectNotify(data) {
      let key = new Date().getTime() + data.pollingTaskName
      let length = Object.keys(this.currentNotification).length
      // 已经存在1条消息
      if (length >= 5) {
        // 先关闭第一个，再添加最新的一个
        this.closeNotify(Object.keys(this.currentNotification)[0])
      }
      let notify = this.$notify({
        title: ['巡检开始', '巡检完成', '巡检未完成'][data.pushType - 1],
        customClass: 'push-alarm-notify',
        type: ['info', 'success', 'warning'][data.pushType - 1],
        message:
          data.pollingTaskName +
          ['已开始巡检', '已完成巡检', '到期未完成'][data.pushType - 1],
        position: 'bottom-right',
        duration: 10000,
        onClose: () => {
          delete this.currentNotification[key]
        },
        onClick: () => {
          this.$router.push({
            name: 'inspectRecord',
          })
        },
      })
      this.currentNotification[key] = notify
    },
    // 一键报警推送消息展示
    pushOneClickAlarmPopup(data) {
      let messageData = {
        pushAlarmTitle: '一键报警',
        iconClass: 'iconfont icon-baojing color-1',
        organizationName: data.addrDesc,
        selfDesc: data.alarmDesc,
        createTime: data.createTime,
        voiceUrl: 'media/alarm.wav',
      }
      // 展示推送内容
      this.openNotify(1, messageData)
    },
    pushOffline(data) {
      let wsData = {}
      if (data.isReset === 0) {
        wsData.pushAlarmTitle = '离线'
        wsData.iconClass = 'iconfont icon-baojing color-1'
        wsData.organizationName = data.organizationName
        wsData.selfDesc = data.instructions
        wsData.createTime = this.$moment(data.createTime).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        wsData.organizationId = data.organizationId
      } else {
        wsData.pushAlarmTitle = '已复位'
        wsData.iconClass = 'iconfont icon-liandong color-4'
        wsData.organizationName = data.organizationName
        wsData.selfDesc = data.instructions
        wsData.createTime = this.$moment(data.resetTime).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        wsData.organizationId = data.organizationId
      }
      this.openNotify(3, wsData)
    },
    unenteredEquipment(data) {
      let wsData = {
        pushAlarmTitle: '未录入设备',
        iconClass: 'iconfont icon-baojing color-1',
        selfDesc: data.desc,
        organizationId: data.orgId,
        createTime: data.time,
      }
      this.openNotify(4, wsData)
    },
    pushAlarmPopup(data) {
      //推送警情推窗
      // 判断警情页面是否打开，打开的话，不管是否在当前页，查询刷新列表。
      // 如果是未复位，只刷新未复位警情列表
      // 如果是已复位，刷新未复位和已复位
      let that = this
      let wsData = data
      let pushAlarmTitle = ''
      let voiceUrl = ''
      let iconClass = 'iconfont '
      let fireTypeMap = {
        10: '报警',
        20: '故障',
        30: '屏蔽',
        40: '联动',
      }
      let fireTypeIconClassMap = {
        10: 'icon-baojing color-1',
        20: 'icon-guzhang1 color-2',
        30: 'icon-pingbi color-8',
        40: 'icon-liandong color-4',
      }
      let msgTypes = ['', '发生', '处理', '复位', '领取']
      // this.pushAlarmDialogData = wsData
      if (wsData.dataFlag) {
        // 已复位
        voiceUrl = 'resource/reset.mp3'
        iconClass += 'icon-fuwei color-3'
        this.$store.commit('setResetAlarmStamp', new Date().getTime())
      } else {
        // 未复位
        // 警情类型分类 报警、故障、屏蔽、联动
        if (wsData.fireTType == 10) {
          voiceUrl = 'media/alarm.wav'
        } else {
          voiceUrl = 'media/fault.wav'
        }
        iconClass += fireTypeIconClassMap[wsData.fireTType]
        this.$store.commit('setUnresetAlarmStamp', new Date().getTime())
      }
      let firetype = fireTypeMap[wsData.fireTType] || ''
      pushAlarmTitle = `${firetype ? '【' + firetype + '】' : ''}${
        msgTypes[data.messageType] || ''
      }`
      wsData.pushAlarmTitle = pushAlarmTitle
      wsData.voiceUrl = voiceUrl
      wsData.iconClass = iconClass
      // 展示推送内容
      this.openNotify(2, wsData)
    },
    formatPicUrl(row) {
      let val = row.resetPicturesUrls || row.picturesUrls
      if (val.indexOf('imageView2') > -1) return val
      if (
        val.indexOf('://file.kshqfire.com') < 0 &&
        val.indexOf('://file.yx-ilink.com') < 0
      )
        return val + '?w=100&h=100'
      if (val.indexOf('imageView2') < 0)
        return val + '?imageView2/2/w/100/h/100/q/75'
      return val
    },
    openNotify(type, data) {
      let notifyType = type
      let key = new Date().getTime() // 用时间戳作为key
      let length = Object.keys(this.currentNotification).length
      // 已经存在1条消息
      if (length >= 1) {
        // 先关闭第一个，再添加最新的一个
        this.closeNotify(Object.keys(this.currentNotification)[0])
      }
      let img = ''
      let buttons = ''
      if (data.resetPicturesUrls || data.picturesUrls) {
        let src = this.formatPicUrl(data)
        img = `<img class="push-alarm-img" src="${src}" onclick="FuncPreviewPushImage(${key})" style="object-fit: cover;">`
      }
      if (notifyType == 2 && data.messageType == 1) {
        data.id = data.recordInfoId
        buttons =
          `<div>` +
          `<button type="button" class="el-button el-button--text el-button--medium" data-id="${data.id}" data-type="2" onclick="FuncDealAlarm(this)">领取</button>` +
          `<button type="button" class="el-button el-button--text el-button--medium" data-id="${data.id}" data-type="1" onclick="FuncDealAlarm(this)" style="margin-left:10px;">处理</button>` +
          `</div>`
      }
      let contentStr =
        `<div class="${img ? 'push-notify-content' : ''}">` +
        `<p>${data.organizationName || ''}${data.organizationName ? '>' : ''}` +
        `${data.selfDesc}</p>` +
        `<p>${data.createTime}</p>${img}${buttons}</div>`
      this.alarmMap[data.id] = { notifyType, key, data }
      let notify = this.$notify({
        title: data.pushAlarmTitle,
        customClass: 'push-alarm-notify',
        iconClass: data.iconClass,
        dangerouslyUseHTMLString: true,
        message: contentStr,
        position: 'bottom-right',
        duration: 10000,
        onClose: () => {
          delete this.currentNotification[key]
          delete this.alarmMap[data.id]
        },
        onClick: () => {
          this.jumpeToUnresetAlarm(notifyType, key, data)
        },
      })
      notify.bizData = data
      this.currentNotification[key] = notify
      if (!this.isMute) {
        // 播放声音
        this.currentAudioUrl = data.voiceUrl
        this.audioIsPlaying = true
      }
    },
    // 关闭单个推送消息窗口
    closeNotify(key) {
      if (this.currentNotification[key]) {
        this.currentNotification[key].close()
        delete this.currentNotification[key]
      }
    },
    // 关闭全部推送消息窗口
    closeAllNotify() {
      this.$notify.closeAll()
      this.currentNotification = {}
    },
    handlePreviewPushImage(key) {
      let bizData = this.currentNotification[key].bizData
      this.onPreview(bizData)
    },
    onPreview(bizData) {
      let arr = []
      if (bizData.resetPicturesUrls) {
        arr.push({
          pic: bizData.resetPicturesUrls,
          resultRegion: bizData.resetRegion,
        })
      }
      if (bizData.picturesUrls) {
        arr.push({
          pic: bizData.picturesUrls,
          resultRegion: bizData.picAlarmRegion,
        })
        if (bizData.aiExtInfo) {
          let extArr = JSON.parse(bizData.aiExtInfo)
          extArr.forEach((n) => {
            arr.push({
              pic: n.imageInfo.pic,
              resultRegion: JSON.stringify(n),
            })
          })
        }
      }
      this.originList = JSON.parse(JSON.stringify(arr))
      this.$nextTick(() => {
        this.$refs.ImageViewer.switchPic(0)
      })
    },
    // 改变消息提醒开关状态
    changeNotificationSwitch(state) {
      if (state === true) {
        if (typeof WebSocket === 'undefined') {
          console.log('您的浏览器不支持socket')
        } else {
          this.int_webSocket()
        }
      } else {
        if (window.ws) {
          window.ws.close()
        }
      }
    },
    // 改变静音状态
    changeMuteState(state) {
      if (state === true) {
        // 静音
        this.isMute = true
        this.audioIsPlaying = false
        document.getElementById('audioPlayer').muted = true
      } else {
        let audioPlayer = document.getElementById('audioPlayer')
        // 非静音
        this.isMute = false
        this.audioIsPlaying = true
        // 解决不能自动播放问题
        if (this.firstLoadAudio) {
          audioPlayer.muted = true // 先静音
          audioPlayer.play() // 播放
          setTimeout(() => {
            audioPlayer.pause() // 暂停
            audioPlayer.muted = false // 再关闭静音
          }, 1500)
          this.firstLoadAudio = false
        }
      }
    },
    // 播放音频结束事件
    playAudioEnd() {
      this.audioIsPlaying = false
      this.currentAudioUrl = ''
    },
    // 播放失败
    playAudioError() {
      this.audioPaused = false
      this.audioIsPlaying = false
      this.currentAudioUrl = ''
    },
    jumpeToUnresetAlarm(type, key, data, dealType) {
      let tabInfo = {}
      let params = {}
      // 推送类别： 1 一键报警  2 警情   3 离线推送
      if (type == 1) {
        tabInfo = {
          name: 'oneClickAlarmList',
          title: '一键报警台账',
        }
      } else if (type == 2) {
        tabInfo = {
          name: 'unresetAlarm',
          title: '未复位警情',
        }
        if (data.dataFlag) {
          //已复位
          tabInfo = {
            name: 'resetAlarm',
            title: '已复位警情',
          }
        }
        params = {
          queryContent: data.fcFacilitiesName || '',
          dealType,
          data,
        }
      } else if (type == 3) {
        tabInfo = {
          name: 'userTransDevice',
          title: '通信服务标识',
        }
        params = {
          organizationId: data.organizationId || '',
        }
      } else if (type == 4) {
        tabInfo = {
          name: 'fireFacstruct',
          title: '物联设备维护',
        }
        params = {
          organizationId: data.organizationId || '',
          windowing: true,
        }
      }
      // 当前路由和目标路由相同时，不跳转
      if (this.$router.currentRoute.name == tabInfo.name) {
        this.$store.commit('setListQueryParam', params)
      } else {
        this.$router.push({
          name: tabInfo.name,
          params,
        })
      }
      this.closeNotify(key)
    },
    menu_police_click() {
      //点击弹出警情关闭弹窗
      let that = this
      that.dialogPolice = true
    },
    addPolice() {
      let that = this
      that.dailogAddpolice = true
      that.realTime_history = !that.realTime_history
      that.policeTitle = '新增'
      //绑定下拉框
      that.orgOptions = []
      getOrgList({ queryType: 0 }).then((data) => {
        that.orgOptions.push.apply(this.orgOptions, data.data)
      })
      getUnitRoles({}).then((res) => {
        that.rolesOptions = res.data
      })
      // console.log(this.orgOptions);
    },
    getSelect() {
      //新增时根据下拉框单位改变获取的数据
      let that = this
      getSysFcfCategoryTree({
        //获取消防系统下拉树
        orgIds:
          that.savehForm.orgId || that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        that.typeList = res.data
      })
      getFbsTree({ organizationId: that.savehForm.orgId }).then((res) => {
        that.treeData = res.data
      })
    },
    handleDetail(row) {
      //提前结束警情
      let that = this
      that
        .$confirm('提前结束后，警情提醒恢复正常。', '注意', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true,
        })
        .then(() => {
          //修改警情提醒状态
          endPoliceClose({
            id: Number(row.id),
            account: this.$store.state.userinfo.accountName,
          }).then((res) => {
            // 刷新页面
            that.menu_alarm_click()
          })
          // 关闭提示框时不关闭弹出层
          that.alarmRemindVisible = true
          // console.log(ids);
        })
        .catch(() => {
          // 关闭提示框时不关闭弹出层
          that.alarmRemindVisible = true
        })
    },
    handleSizeChange(pageSize) {
      this.showHistory(1, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.showHistory(currentPage)
    },
    showHistory(pageIndex, pageSize) {
      //展示历史记录
      let that = this
      if (pageIndex && typeof pageIndex != 'object') {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }

      that.realTime_history = false
      that.history_realTime = true
      that.policeTitle = '历史记录'
      getPoliceCloseRecords({
        queryType: 1,
        pageIndex: that.currentPage - 1,
        pageSize: that.pageSize,
        type: 1,
        orgIds: that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        that.policeHistoryTableData = res.data
        that.total = res.total
        let data = new Date()
        let dataMinutes = data.toLocaleString('chinese', { hour12: false })
        for (var i = 0; i < that.policeHistoryTableData.length; i++) {
          that.policeHistoryTableData[i].type = '已结束'
          that.policeHistoryTableData[i].beginTime =
            that.policeHistoryTableData[i].beginTime.substring(0, 16) +
            ' 至 ' +
            that.policeHistoryTableData[i].endTime.substring(0, 16)
        }
      })
    },
    showRealTime_history() {
      //展示实时关闭提醒记录
      let that = this
      that.realTime_history = true
      that.history_realTime = !that.history_realTime
      that.policeTitle = '未结束的关闭措施'
    },
    savePolice(formName) {
      //添加警情关闭提醒
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          that.dailogAddpolice = false
          that.realTime_history = true
          that.policeTitle = '未结束的关闭措施'
          let pushRoleIds = that.rolesOptions
          for (var i = 0; i < pushRoleIds.length; i++) {
            for (var j = 0; j < that.savehForm.roles.length; j++) {
              if (pushRoleIds[i].id == that.savehForm.roles[j]) {
                pushRoleIds.splice(i, 1)
              }
            }
          }
          for (var i = 0; i < pushRoleIds.length; i++) {
            pushRoleIds[i] = pushRoleIds[i].id
          }
          let parames = {
            orgId: that.savehForm.orgId,
            systemId: that.savehForm.fireSystemId,
            fbsId: that.savehForm.build,
            shieldRoleIds: String(that.savehForm.roles),
            pushRoleIds: String(pushRoleIds),
            beginTime: that.savehForm.time[0],
            endTime: that.savehForm.time[1],
            remark: that.savehForm.remark,
            createAccount: this.$store.state.userinfo.accountName,
          }
          this.loading = true
          //let params = JSON.stringify(parames)
          saveOrUpdatePoliceCloseRecord({
            orgId: that.savehForm.orgId,
            systemId: that.savehForm.fireSystemId,
            fbsId: that.savehForm.build,
            shieldRoleIds: String(that.savehForm.roles),
            pushRoleIds: String(pushRoleIds),
            beginTime: that.savehForm.time[0],
            endTime: that.savehForm.time[1],
            remark: that.savehForm.remark,
            createAccount: this.$store.state.userinfo.accountName,
          }).then((res) => {
            that.selectFlag = true
            that.menu_alarm_click()
            that.savehForm.orgId = ''
            that.savehForm.fireSystemId = ''
            that.savehForm.build = ''
            that.savehForm.roles = ''
            that.savehForm.time = ''
            that.savehForm.remark = ''
            this.loading = false
          })
        }
      })
    },
    cancelPolice() {
      //取消
      let that = this
      that.dailogAddpolice = false
      that.realTime_history = true
      that.policeTitle = '等待结束的警情提醒'
      that.policeWidth = 1200
    },
    tableRowClassName({ row, columnIndex }) {
      // 声明一个变量
      const colors = {
        执行中: 'red',
        未开始: '#FFC73B',
      }

      if (columnIndex === 1) {
        // columnIndex 选择要改变的列数
        return { color: colors[row.type] } // row.state根据 state 中的字段进行判断
      }
    },
    /* 打开梯控弹框 */
    openElevatorController() {
      this.formInline = {
        orgIds: this.$store.state.userinfo.organizationIds,
        fbsId: '',
        queryContent: '',
        status: 2,
        queryType: 1,
        pageIndex: 0,
        pageSize: 10,
      }
      this.elevatorVisible = true
    },
    /* 关闭梯控弹框 */
    closeElevatorController() {
      this.elevatorVisible = false
      this.handleFormVisible = false
    },
    showHandleForm(val) {
      // console.log(val);
      this.handleFormVisible = val
    },
    hideHandleForm(val) {
      // console.log(val);
      this.handleFormVisible = val
    },
  },
  watch: {
    orgIdSelect(val, oldVal) {
      if (val !== oldVal) {
        if (val) {
          let that = this
          that.selectFlag = false
          that.getSelect()
        }
      }
    },
    timeSelect(val, oldVal) {
      if (val && val !== oldVal) {
        let d = new Date(val[0])
        d.setDate(d.getDate() + 1)
        let m = d.getMonth() + 1
        let endTime =
          d.getFullYear() +
          '-' +
          m +
          '-' +
          d.getDate() +
          ' ' +
          val[0].slice(11, 16) +
          ':00'
        if (new Date(val[1]).getTime() > new Date(endTime).getTime()) {
          this.$message({
            message: '不能超过24小时，请重新选择 ',
            type: 'warning',
          })
          this.savehForm.time = ''
        }
      }
    },
  },
  computed: {
    orgIdSelect() {
      return this.savehForm.orgId
    },
    timeSelect() {
      return this.savehForm.time
    },
  },
}
</script>

<style lang="scss" scoped>
.header-wrap {
  padding: 0;
  height: 48px;
  background-color: #446bde;
  color: #fff;
  line-height: 48px;
}
.logo-link {
  float: left;
  width: 180px;
  height: 48px;
  padding: 0 15px;
}
.logo-link .el-image {
  max-width: 100%;
}
.menu-nav-wrap {
  display: flex;
  justify-content: space-between;
}
.time-wrap {
  float: right;
  display: flex;
  align-items: center;
  padding-left: 20px;
  // width: 270px;
  height: 48px;
  box-sizing: border-box;
  .iconfont,
  .el-icon {
    margin-right: 15px;
    font-size: 22px;
    cursor: pointer;
  }
  .userinfo-wrap {
    color: #fff;
    margin-right: 15px;
    .el-dropdown-link {
      height: 48px;
      display: flex;
      align-items: center;
      .user-name {
        margin-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 80px;
        text-align: right;
      }
      .header-user-img {
        width: 38px;
        height: 38px;
        border-radius: 50%;
        /*border: 1px solid #fff;*/
      }
    }
  }
}
.time {
  margin-right: 20px;
}
.form-download {
  .el-tab-pane {
    padding: 0;
  }
  .el-tabs {
    height: 350px;
  }
  .qrcode-content {
    float: left;
    width: 50%;
    text-align: center;
    p {
      line-height: 30px;
    }
  }
  #container_android,
  #container_ios {
    height: 180px;
    width: 180px;
    margin-bottom: 20px;
    margin-top: 20px;
  }
  .ios-btn,
  .android-btn {
    width: 140px;
    height: 38px;
    display: inline-block;
  }
  .ios-btn {
    background: url(../../assets/images/download/ios-btn.png) no-repeat center
      center;
  }
  .android-btn {
    background: url(../../assets/images/download/android-btn.png) no-repeat
      center center;
  }
  .planClient-btn {
    height: 160px;
    width: 120px;
    margin: auto;
    background-position: center center;
    background-repeat: no-repeat;
    cursor: pointer;
  }
  .videoClient-btn {
    height: 160px;
    width: 128px;
    margin: auto;
    background: url(../../assets/images/download/vedio.png) no-repeat center
      center;
    cursor: pointer;
  }
}
.header_police_history {
  position: absolute;
  top: -2px;
  margin-left: 88%;
  .el-button--text {
    font-size: 16px;
  }
}
.el-form-item {
  width: 100%;
}
.iconfont-red {
  color: #e44d60;
}
.head_police_remind {
  margin-left: 149px;
  margin-top: -10px;
  margin-bottom: 20px;
  color: #e54c2e;
}
</style>
<style lang="scss">
.push-notify-content {
  position: relative;
  padding-right: 120px;
  min-height: 100px;
  .push-alarm-img {
    position: absolute;
    top: 50%;
    margin-top: -50px;
    right: 0;
    width: 100px;
    height: 100px;
    cursor: pointer;
  }
}
.police_dialog {
  .el-dialog__title {
    float: left !important;
  }
}
.add_Polic {
  .el-form-item__content {
    width: 570px !important;
  }
}

.build_tree {
  .el-form--inline .el-form-item__content {
    display: inline-block;
    vertical-align: top;
    width: 504px;
  }
}
.input_length {
  width: 504px !important;
}
.el-range-editor.is-disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
  width: 504px;
}
.popover_diaglo {
  height: 450px;
  overflow: auto;
}
.push-alarm-notify {
  width: 450px;
  cursor: pointer;
  .el-notification__icon {
    font-size: 18px;
  }
  .el-notification__group {
    width: 100%;
    .el-notification__content {
      color: #8f8f8f;
    }
  }
}
.mute-checkbox {
  &.is-checked {
    .el-checkbox__inner {
      background-color: rgb(19, 206, 102);
      border-color: rgb(19, 206, 102);
    }
    .el-checkbox__label {
      color: rgb(19, 206, 102);
    }
  }
}
.el-drawer :focus {
  outline: 0;
}
</style>
